var mongodb = require('mongodb');
var fs = require('fs');
var BSON = require('mongodb').pure().BSON;
var ObjectID = require('mongodb').ObjectID;
var Grid = require('mongodb').Grid;

/*
if(process.env.VCAP_SERVICES){
    var env = JSON.parse(process.env.VCAP_SERVICES);
    var mongo = env['mongodb-1.8'][0].credentials;
}
else{
    var mongo = {
            "hostname":"ds039078.mongolab.com",
            "port":39078,
            "username":"admin",
            "password":"mta2013",
            "db":"activiteam"
    };
}

var generate_mongo_url = function(obj){
    obj.hostname = (obj.hostname || 'localhost');
    obj.port = (obj.port || 27017);
    obj.db = (obj.db || 'test');

    if(obj.username && obj.password){
        return "mongodb://" + obj.username + ":" + obj.password + "@" + obj.hostname + ":" + obj.port + "/" + obj.db;
    }
    else{
        return "mongodb://" + obj.hostname + ":" + obj.port + "/" + obj.db;
    }
};
*/
var mongourl = process.env.MONGOLAB_DB ? process.env.MONGOLAB_DB : 'mongodb://admin:mta2013@ds039078.mongolab.com:39078/activiteam';//generate_mongo_url(mongo);

//adding picture to user/comment:
//INPUT: the request must contain the file, and req.type=user/comment, req.id for comments and session for user.
//OUTPUT: {upload:success/error/not logged}
exports.uploadPicture = function(req, res){
    //if this is a user photo, check he is logged in:
    if (req.body.type=="user" && !req.session.myEmail){
        res.send({"upload":"not logged"});
        return;
    }
    mongodb.connect(mongourl, function(err, db) {
        if (err) {
            res.send({"upload" : "error"});
            return;
        } else {
            fs.readFile(req.files.fileUpload.path,function(err,data){
                var grid = new Grid(db,'fs');
                var buffer = new Buffer(data);
                grid.put(buffer,{metadata:{},filename:req.files.fileUpload.name,content_type:req.files.fileUpload.type}, function(err,fileInfo){
                    if (err){
                        res.send({"upload":"error"});
                        db.close();
                        return;
                    }
                    else{
                        //The image was uploaded successfully!
                        //check if this is a user photo:
                        if (req.body.type=="user"){
                            //find the user:
                            db.collection('users',function(err,collection){
                                if (err){
                                    res.send({"upload":"error"});
                                    db.close();
                                    return;
                                }
                                else{
                                    collection.update({"email":req.session.myEmail},
                                            {$set:{"photoid":fileInfo._id}},{safe:true},
                                            function(err,temp){
                                                if (err){
                                                    res.send({"update":"error"});
                                                    db.close();
                                                    return;
                                                } else {
                                                    res.send({"update":"success"});
                                                    db.close();
                                                    return;
                                                }

                                            });
                                }
                            });
                        } else {
                            //this is a comment photo:
                            db.collection('comments',function(err,collection){
                                if (err){
                                    res.send({"upload":"error"});
                                    db.close();
                                    return;
                                } else {
                                    collection.update({"_id":ObjectID(req.body.id)},
                                            {$set:{"photoid":fileInfo._id}},{safe:true},
                                            function(err,temp){
                                                if (err){
                                                    res.send({"upload":"error"});
                                                    db.close();
                                                    return;
                                                } else {
                                                    res.send({"update":"success"});
                                                    db.close();
                                                    return;
                                                }
                                            });
                                }
                            });
                        }
                    }
                });
            });
        }});
};

//getting a picture from id
//input: the picture id {id:___}
//output: the picture's data.
exports.getPicture = function(req, res){
    mongodb.connect(mongourl, function(err, db) {
        if (err) {
            res.send({"error" : "error"});
            console.log(err.message);
            return;
        } else {
            var grid =new Grid(db,'fs');
            grid.get(ObjectID(req.params.picid),function(err,data){
                if (err){
                    res.send({"error":"error"});
                    console.log(err.message);
                    db.close();
                    return;
                }
                console.log("Retrieved data: " + data.toString());
                res.send(data);
                db.close();
                return;
            });
        }
    });
};